<template>
	<div>
		<div>
			<el-form ref="searchForm" :model="searchForm" inline>
				<el-form-item label="题目" prop="name">
					<el-input v-model="searchForm.name" clearable placeholder="请输入题目"></el-input>
				</el-form-item>
				<el-form-item label="">
					<el-button type="primary" icon="el-icon-search" @click="handleSearch">搜 索</el-button>
					<el-button icon="el-icon-refresh-left" @click="resetForm">重 置</el-button>
				</el-form-item>
			</el-form>
		</div>
		<el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
		<el-button type="danger" icon="el-icon-remove-outline" @click="batchDelete()">批量删除
		</el-button>
		<el-button type="success" @click="downloadText">下载导入模板</el-button>
		<el-button type="primary" @click="daoruDialog = true">批量导入试题</el-button>
		<el-button icon="el-icon-back" @click="back()">返回题库</el-button>
		<el-container
			style="height: auto; border: 1px solid #eeel;margin-top: 10px;box-shadow: 0px 0px 5px 2px gainsboro;">
			<el-aside width="200px" style="background-color: rgb(238, 241, 246)">
				<el-menu :default-openeds="['1']" :default-active="'1'">
					<el-submenu index="1">
						<template slot="title"><i class="el-icon-s-management"></i>题型</template>
						<el-menu-item index="1" @click="sreachList()">
							<i class="el-icon-s-promotion"></i>
							<span slot="title">全部</span>
						</el-menu-item>
						<el-menu-item index="2" @click="sreachList('单项选择题')">
							<i class="el-icon-s-promotion"></i>
							<span slot="title">单项选择题</span>
						</el-menu-item>
						<el-menu-item index="3" @click="sreachList('多项选择题')">
							<i class="el-icon-s-promotion"></i>
							<span slot="title">多项选择题</span>
						</el-menu-item>
						<el-menu-item index="4" @click="sreachList('判断题')">
							<i class="el-icon-s-promotion"></i>
							<span slot="title">判断题</span>
						</el-menu-item>
						<el-menu-item index="5" @click="sreachList('填空题')">
							<i class="el-icon-s-promotion"></i>
							<span slot="title">填空题</span>
						</el-menu-item>
						<el-menu-item index="6" @click="sreachList('简答题')">
							<i class="el-icon-s-promotion"></i>
							<span slot="title">简答题</span>
						</el-menu-item>
					</el-submenu>
				</el-menu>
			</el-aside>
			<el-container>
				<el-main>
					<div style="font-size: 22px;margin: 0px 0px 10px 0px;">
						题库名称:{{title}}
					</div>
					<el-table ref="multipleTable" :data="listData" tooltip-effect="dark" style="width: 100%"
						:header-cell-style="headClass" :cell-style="rowClass">
						<el-table-column type="selection" width="55"></el-table-column>
						<el-table-column label="题序" type="index" width="50">
						</el-table-column>
						<el-table-column prop="name" label="题目"></el-table-column>
						<el-table-column prop="type" label="题型"></el-table-column>
						<el-table-column prop="options" label="选择题选项">
							<template slot-scope="scope">
								<!-- <el-input v-model="item.value" v-for="(item,i) in scope.row.options" :key="i" style="margin: 3px 0px;" disabled>
								    <template slot="prepend">{{item.label}}</template>
								  </el-input> -->
								<div v-for="item in scope.row.options">
									{{item.label}}:{{item.value}}
								</div>
							</template>
						</el-table-column>
						<el-table-column prop="answerOption" label="正确答案"></el-table-column>
						<el-table-column prop="score" label="分值"></el-table-column>
						<el-table-column prop="user" label="创建人"></el-table-column>
						<el-table-column label="操作" width="200" fixed="right">
							<template slot-scope="scope">
								<el-button icon="el-icon-edit-outline" @click="handleEdit(scope.$index, scope.row)">编辑
								</el-button>
								<el-button type="danger" icon="el-icon-remove-outline"
									@click="handleDelete(scope.$index, scope.row)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
					<div style="margin-top: 20px">
						<el-pagination @current-change="currentChange" @size-change="sizeChange"
							:page-size="pageInfo.pageSize" :current-page="pageInfo.currentPage" background
							layout="sizes, prev, pager, next" :total="total">
						</el-pagination>
					</div>
				</el-main>
			</el-container>
		</el-container>
		<el-dialog :title="formData.id?'编辑':'新增'" :visible.sync="isDrawerDialog" size="400px" direction="rtl"
			:wrapper-closable="false">
			<div class="demo-drawer_content" style="padding-right: 40px;box-sizing: border-box">
				<el-form :model="formData" label-width="100px" class="demo-ruleForm">
					<slot name="content">
						<el-form-item label="题目">
							<el-input v-model="formData.name"></el-input>
						</el-form-item>
						<el-form-item label="题型">
							<el-select clearable v-model="formData.type" placeholder="请选择" style="width: 20%"
								:disabled="formData.id?true:false">
								<el-option v-for="item in questionType" :key="item" :label="item" :value="item">
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="选择题选项" v-if="formData.type==='单项选择题' || formData.type==='多项选择题'">
							<!-- <el-input v-model="selectList." v-for="(item,i) in selectList" :key="i"></el-input> -->
							<el-input placeholder="请输入选项内容" v-model="item.value" v-for="(item,i) in selectList" :key="i" style="margin: 3px 0px;">
							    <template slot="prepend">{{item.label}}</template>
							  </el-input>
						</el-form-item>
						<!-- 	<el-form-item label="选择题选项" v-if="formData.type==='多项选择题'">
							<el-input v-model="initialCheckboxes" v-for="item in initialCheckboxes" :key="item">
							</el-input>
						</el-form-item> -->
						<div style="text-align: center;margin: 10px 0px;"
							v-if="formData.type==='单项选择题' || formData.type==='多项选择题'">
							<el-button type="primary" icon="el-icon-circle-plus-outline" @click="addOption">添加新选项
							</el-button>
						</div>
						<!-- <div style="text-align: center;margin: 10px 0px;" v-if="formData.type==='多项选择题'">
							<el-button type="primary" icon="el-icon-circle-plus-outline" @click="addCheckbox">添加新选项
							</el-button>
						</div> -->
						<el-form-item label="正确答案" v-if="formData.type==='填空题'||formData.type==='简答题'">
							<el-input type="textarea" :rows="7" v-model="formData.answer"></el-input>
						</el-form-item>
						<el-form-item label="正确答案" v-if="formData.type==='单项选择题'">
							<el-radio v-model="formData.answer" :label="item.value" v-for="(item,i) in selectList"
								:key="i">{{item.label}}:{{item.value}}</el-radio>
						</el-form-item>
						<el-form-item label="正确答案" v-if="formData.type==='多项选择题'">
							<el-checkbox-group v-model="checkedItems">
								<el-checkbox :label="item.label" v-for="(item,i) in selectList" :key="i">
									{{item.label}}:{{item.value}}
								</el-checkbox>
							</el-checkbox-group>
						</el-form-item>
						<!-- <el-form-item label="正确答案" v-if="formData.type==='多项选择题'">
							<el-checkbox-group v-model="formData.answer">
								<el-checkbox :label="selectList[i]" v-for="(item,i) in selectList"
								:key="i"></el-checkbox>
							</el-checkbox-group>
						</el-form-item> -->
						<el-form-item label="正确答案" v-if="formData.type==='判断题'">
							<el-radio v-model="formData.answer" label="对"></el-radio>
							<el-radio v-model="formData.answer" label="错"></el-radio>
						</el-form-item>
						<el-form-item label="试题解析">
							<el-input type="textarea" :rows="7" v-model="formData.analysis"></el-input>
						</el-form-item>
						<el-form-item label="分值">
							<el-input type="number" v-model="formData.score" style="width: 10%;"></el-input>
						</el-form-item>
					</slot>
				</el-form>
			</div>
			<div class="demo-drawer_footer" style="display: flex; justify-content: space-around;">
				<el-button @click="isDrawerDialog=false">取消</el-button>
				<el-button type="primary" @click="submit">提交</el-button>
			</div>
		</el-dialog>
		<el-dialog title="批量导入" :visible.sync="daoruDialog">
			<el-upload ref="upload" class="upload-demo" :auto-upload="false" :on-change="handleChange"
				:before-upload="beforeUpload" :http-request="handleHttpRequest" accept=".xlsx, .xls">
				<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
				<el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传文件
				</el-button>
				<div slot="tip" class="el-upload__tip">只能上传xlsx/xls文件</div>
			</el-upload>
		</el-dialog>
	</div>
</template>

<style scoped>
	.el-header {
		background-color: #B3C0D1;
		color: #333;
		line-height: 60px;
	}
	
	.el-input.is-disabled>>>.el-input__inner {
	    background-color:white;
	    border-color: #E4E7ED;
	    color: #606266;
	    cursor: not-allowed;
	}

	.el-aside {
		color: #333;
	}
</style>

<script>
	import utils from "@/utils/utils";
import { Option } from "element-ui";
	export default {
		data() {
			const item = {
				date: '2016-05-02',
				name: '王小虎',
				address: '上海市普陀区金沙江路 1518 弄'
			};
			return {
				tableData: Array(20).fill(item),
				isDrawerDialog: false,
				listData: [],
				daoruDialog: false,
				total: 0,
				title: '',
				//分页详情
				pageInfo: {
					//当前页
					pageNum: 1,
					//分页大小
					pageSize: 10
				},
				//搜索
				searchForm: {
					name: "",
					type: ''
				},
				formData: {

				},
				//删除数据的id
				ids: [],
				initialCheckboxes: ['A', 'B', 'C', 'D'],
				checkedItems: [],
				allCheckboxes: [],
				checkId: '',
				userInfo: utils.getUserInfo(),
				questionType: [
					"单项选择题",
					"多项选择题",
					"判断题",
					"填空题",
					"简答题"
				],
				selectList: [{
						label: 'A',
						value: ''
					},
					{
						label: 'B',
						value: ''
					},
					{
						label: 'C',
						value: ''
					},
					{
						label: 'D',
						value: ''
					}
				],
				currentLabel:'D',
				nextLetter: 'E'.charCodeAt(0),
				defaultList: [{
						label: 'A',
						value: ''
					},
					{
						label: 'B',
						value: ''
					},
					{
						label: 'C',
						value: ''
					},
					{
						label: 'D',
						value: ''
					},
				]
			}
		},
		created() {

		},
		mounted() {
			this.getPageList()
			this.title = this.$route.query.name
			this.checkId = this.$route.query.id
		},
		computed: {
			sortedSelectList() {
				// 虽然在这个例子中我们不需要排序，但如果你想要确保数组始终有序，可以这样做：  
				// return this.selectList.slice().sort((a, b) => a.localeCompare(b));  
				// 由于我们是按顺序添加的，所以直接返回原数组即可  
				return this.selectList;
			},
		},
		methods: {
			//新增单项选择题单选框
			addOption() {
				// 获取当前最后一个 label 的字符
				      const lastLabel = this.currentLabel;
				 
				      // 计算下一个字母（这里简单处理，不考虑超出 'Z' 的情况）
				      const nextLabel = String.fromCharCode(lastLabel.charCodeAt(0) + 1);
				 
				      // 创建新对象并添加到 selectList 数组中
				      this.selectList.push({ label: nextLabel, value: '' });
				 
				      // 更新 currentLabel 为新添加的 label
				      this.currentLabel = nextLabel;
			},
			//新增多项选择题复选框
			addCheckbox() {
				// 生成一个新的复选框标签（例如，下一个字母）  
				const nextLabel = String.fromCharCode(
					// 找到当前 allCheckboxes 中最后一个标签的字符码，然后加1  
					this.allCheckboxes.reduce((max, label) => Math.max(max, label.charCodeAt(0)), 'Z'
						.charCodeAt(0) -
						1) + 1
				);
				// 如果生成的标签超出了字母表范围（例如，超过了'Z'），则循环回'A'  
				// 但在这个例子中，我们简单地避免添加超出'Z'的标签  
				if (nextLabel <= 'Z') {
					this.allCheckboxes.push(nextLabel);
				} else {
					this.$message.warning('无法添加更多复选框，已超出字母表范围！');
				}
			},
			getPageList() {
				let data = Object.assign(this.searchForm, this.pageInfo)
				data.bankId = this.$route.query.id
				this.$axios.get("/examQuestion/page", {
					params: data
				}).then(res => {
					this.listData = res.data.list
					this.listData.forEach(item=>{
						item.options = JSON.parse(item.options)
					})
					console.log(this.listData,123)
					this.total = res.data.total
				})
			},
			sreachList(type) {
				console.log(type)
				if (type) {
					this.searchForm.type = type
				} else {
					this.searchForm.type = ''
				}
				this.getPageList()
			},
			back() {
				this.$router.push({
					path: '/examQuestionManage',
				})
			},
			handleChange(file, fileList) {
				// 处理文件选择后的逻辑
			},
			beforeUpload(file) {
				const isExcel =
					file.type ===
					'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
					file.type === 'application/vnd.ms-excel';
				if (!isExcel) {
					this.$message.error('上传文件只能是 Excel 格式!');
					return false; // 阻止上传
				}
				return true; // 允许上传
			},
			handleHttpRequest(file) {
				console.log(123, file.file)
				// 这里实现自定义的上传逻辑
				// 例如，使用 axios 发送 POST 请求到服务器
				const formData = new FormData();
				formData.append('file', file.file);
				this.$axios.post('/examQuestion/importQuestion?id=' + this.checkId, formData).then(res => {
					// 处理上传成功的逻辑
					this.$message.success('上传成功!');
					console.log('上传', res)
					this.daoruDialog = false
					this.getPageList()
				}).catch(error => {
					// 处理上传失败的逻辑
					// this.$message.error('上传失败!');
				});
			},
			submitUpload() {
				this.$refs.upload.submit();
				// this.handleHttpRequest(file);
			},
			downloadText() {
				var a = document.createElement('a')
				a.href = 'http://kaoshi.gxkaijie.cn/api1/question.xlsx'
				console.log(a.href)
				a.download = '导入模板.xlsx'
				a.style.display = 'none'
				document.body.appendChild(a)
				a.click()
				a.remove()
			},
			resetForm() {
				this.$refs['searchForm'].resetFields();
			},
			headClass() { //表头居中显示
				return "text-align:center;font-size:14px;"
			},
			rowClass() { //表格数据居中显示
				return "text-align:center;font-size:13px;"
			},
			//选择分页
			currentChange(e) {
				this.pageInfo.pageNum = e
				this.getPageList()
			},
			//改变分页数量
			sizeChange(e) {
				this.pageInfo.pageSize = e
				this.getPageList()
			},
			//搜索
			handleSearch() {
				this.pageInfo.pageNum = 1
				this.getPageList()
			},
			//单个删除
			handleDelete(index, row) {
				this.batchDelete([row])
			},
			//批量删除
			batchDelete(rows) {
				
				if (!rows) {
					rows = this.$refs.multipleTable.selection;
				}
				this.$confirm(`此操作将永久删除数据, 是否继续?`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
					center: true
				}).then(() => {
					//批量删除数据
					rows.forEach(j=>{
						j.options = JSON.stringify(j.options)
					})
					let ids = rows.map(item => item);
					this.$axios.delete("/examQuestion/delBatch", {
						data: ids
					}).then(res => {
						if (res.code === 200) {
							this.$message({
								message: res.msg,
								type: 'success'
							});
							this.getPageList()
						}
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
					this.$refs.multipleTable.clearSelection();
				});
			},
			//提交数据
			submit() {
				//新增
				this.formData.bankId = this.$route.query.id
				if (!this.formData.id) {
					//单项选择题和多项选择题才能有进行配置
					if (this.formData.type === '单项选择题') {
						console.log(this.selectList, '单选')
						this.selectList.forEach(item=>{
							if(item.value == this.formData.answer){
								this.formData.answerOption = item.label
							}
						})
						console.log(this.formData,'all')
						this.formData.options = JSON.stringify(this.selectList)
					}
					if (this.formData.type === '多项选择题') {
						this.formData.answer = []
						this.formData.answerOption = JSON.stringify(this.checkedItems)
						console.log(this.checkedItems,'多选')
						this.selectList.forEach(item=>{
							this.checkedItems.forEach(j=>{
								if(item.label == j){
									this.formData.answer.push(item.value)
								}
							})
						})
						console.log(this.formData.answerOption,this.formData.answer)
						this.formData.answer = JSON.stringify(this.formData.answer)
						this.formData.options = JSON.stringify(this.selectList)
					}
					console.log(this.formData, 52)
					this.$axios.post("/examQuestion/add", this.formData).then(res => {
						if (res.code === 200) {
							this.isDrawerDialog = false
							this.$message({
								message: res.msg,
								type: 'success'
							});
							this.getPageList()
						}
					})
				} else {
					//更新
					if (this.formData.type === '单项选择题') {
						console.log(this.selectList, '单选')
						this.selectList.forEach(item=>{
							if(item.value == this.formData.answer){
								this.formData.answerOption = item.label
							}
						})
						console.log(this.formData,'all')
						this.formData.options = JSON.stringify(this.selectList)
					}
					if (this.formData.type === '多项选择题') {
						this.formData.answer = []
						this.formData.answerOption = JSON.stringify(this.checkedItems)
						console.log(this.checkedItems,'多选')
						this.selectList.forEach(item=>{
							this.checkedItems.forEach(j=>{
								if(item.label == j){
									this.formData.answer.push(item.value)
								}
							})
						})
						console.log(this.formData.answerOption,this.formData.answer)
						this.formData.answer = JSON.stringify(this.formData.answer)
						this.formData.options = JSON.stringify(this.selectList)
					}
					this.$axios.put("/examQuestion/update", this.formData).then(res => {
						if (res.code === 200) {
							this.isDrawerDialog = false
							this.$message({
								message: res.msg,
								type: 'success'
							});
							this.getPageList()
						}
					})
				}
			},
			//添加数据
			handleAdd() {
				let a = [{
						label: 'A',
						value: ''
					},
					{
						label: 'B',
						value: ''
					},
					{
						label: 'C',
						value: ''
					},
					{
						label: 'D',
						value: ''
					},
				]
				this.formData = {}
				this.isDrawerDialog = true
				// 重置selectList为初始选项  
				this.selectList = a;
				this.nextLetter = 'E'.charCodeAt(0);
			},
			//编辑
			handleEdit(index, row) {
				this.formData = Object.assign({}, row)
				console.log(this.formData,'xu')
				if (this.formData.type === '单项选择题' || this.formData.type === '多项选择题') {
					this.selectList = this.formData.options
				}
				this.isDrawerDialog = true
			},
		}
	};
</script>
